//
//  PhotoSelector.swift
//  照片选择器43534
//
//  Created by gzxzmac on 16/4/3.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

import HMImagePicker

private let reuseIdentifier = "Cell"

class Person: NSObject {
    var name: String?
}

class PhotoSelectorViewController: UICollectionViewController {
    
    /// 选中的图片
    var photos: [UIImage] = [UIImage]()
    
    /// 当前选中图片的PHAsset,只有把设置传给对象到时候才能默认选中对应的图片
    var selectedAssets: [PHAsset]?
    
    private let MaxCount = 6
    
    /// 点击cell的indexPath
    var clickIndexPath: NSIndexPath?
    
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Swift的创建工程时,不要中文加数字
        var persons = [Person]()
        persons.append(Person())
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        self.collectionView!.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        
        // 设置collectionView的内边距
        self.collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
//        layout.sectionInset = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
    }
    // MARK: UICollectionViewDataSource

//    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 6
//    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当图片数量小于最大张数时,cell的数量 = 图片数量 + 1
        // 当图片数量等于最大张数时,cell的数量 = 图片数量
        return photos.count < MaxCount ? photos.count + 1 : photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
    
        cell.backgroundColor = UIColor.brownColor()
        
        // 显示图片
        if indexPath.item < photos.count {
            // 有图片,才去图片图片
            cell.image = photos[indexPath.item]
        } else {
            // 加号按钮,防止复用,需要在设置加号图片
            cell.setupAddButton()
        }
        
        // 5.设置代理
        cell.delegate = self
    
        return cell
    }
}

// MARK: - 扩展
// 6.实现代理
extension PhotoSelectorViewController: PhotoSelectorCellDelegate {
    // 7.实现代理方法
    func photoSelectorCellDidClickDeleteButton(cell: PhotoSelectorCell) {
        // 找到点击的那个cell的删除按钮
        let indexPath = collectionView?.indexPathForCell(cell)
        
        // 在找到那张图片
        photos.removeAtIndex(indexPath!.item)
        
        // 刷新collectionView
        collectionView?.reloadData()
    }
    
    func photoSelectorCellDidClickAddButton(cell: PhotoSelectorCell) {
        // 系统的照片选择器
//        let picker = UIImagePickerController()
        let picker = HMImagePickerController(selectedAssets: self.selectedAssets)
        
        picker.pickerDelegate = self
        picker.maxPickerCount = 6
//        picker.delegate = self
        
        // 记录下点击cell的位置
        clickIndexPath = collectionView?.indexPathForCell(cell)
        
        presentViewController(picker, animated: true, completion: nil)
    }
}

extension PhotoSelectorViewController: HMImagePickerControllerDelegate {
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        photos = images
        
        self.selectedAssets = selectedAssets
        
        // 刷新collectionView
        collectionView?.reloadData()
        
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - 照片选择代理
// protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>    // 同时实现2个代理
extension PhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 当选中图片的时候回调用这个方法,只要实现了这个方法,就需要自己来关闭
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print("选中了: \(image)")
        let newImage = image.scaleImage()
        
        // 如果点击的是加号就添加图片,如果点击的是图片就修改图片
        if clickIndexPath!.item == photos.count {
            // 点击的是加号按钮
            photos.append(newImage)
        } else {
            // 之前点击的是图片,修改图片
            photos[clickIndexPath!.item] = newImage
        }
        
        // 刷新collectionView
        collectionView?.reloadData()
        
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - cell点击的代理
// 1.定义协议
protocol PhotoSelectorCellDelegate: NSObjectProtocol {
    // 2.定义方法
    func photoSelectorCellDidClickAddButton(cell: PhotoSelectorCell)
    
    func photoSelectorCellDidClickDeleteButton(cell: PhotoSelectorCell)
}

// MARK: - 自定义cell
class PhotoSelectorCell: UICollectionViewCell {
    
    /// 要显示的图片
    var image: UIImage? {
        didSet {
            // 将图片设置给按钮
            addButton.setImage(image, forState: UIControlState.Normal)
            
            // 显示删除按钮
            deleteButton.hidden = false
        }
    }
    
    // 3.定义代理属性
    weak var delegate: PhotoSelectorCellDelegate?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    // 设置加号按钮
    func setupAddButton() {
        // 设置图片
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        // 隐藏删除按钮
        deleteButton.hidden = true
    }
    
    private func prepareUI() {
        // 1.添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 2.添加约束
        // VFL
        // addButton
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        
        // deleteButton, 水平方向和父控件重合 : V:|-(-10)-[db]
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["db" : deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["db" : deleteButton]))
    }
    
    // MARK: - 按钮点击事件
    @objc private func didClickAddButton() {
        // 4.调用代理
        delegate?.photoSelectorCellDidClickAddButton(self)
    }
    
    @objc private func didClickDeleteButton() {
        // 4.调用代理
        delegate?.photoSelectorCellDidClickDeleteButton(self)
    }
    
    // MARK: - 懒加载
    /// 加号按钮(图片)
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        // 如果使用背景图片,到时候不好设置图片的填充模型
//        button.setBackgroundImage(<#T##image: UIImage?##UIImage?#>, forState: <#T##UIControlState#>)
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didClickAddButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置图片的填充模式
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        return button
    }()
    
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didClickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}
